package com.dycx.cms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dycx.cms.mapper.AdTypeMapper;
import com.dycx.cms.dto.AdTypeDTO;
import com.dycx.cms.entity.AdTypeDO;
import com.dycx.cms.service.AdTypeService;
import com.dycx.cms.vo.AdTypeVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


@Service
@AllArgsConstructor
public class AdTypeImpl extends ServiceImpl<AdTypeMapper, AdTypeDO> implements AdTypeService {

    @Override
    public Boolean delete(int typeId) {
        return this.removeById(typeId);
    }

    /**
     * 添加
     *
     * @param adTypeDto
     * @return
     */
    @Override
    public Boolean add(AdTypeDTO adTypeDto) {
        AdTypeDO adTypeEntity = BeanUtil.toBean(adTypeDto, AdTypeDO.class);

        boolean result = this.save(adTypeEntity);
        adTypeDto.setId(adTypeEntity.getId());
        return result;
    }

    /**
     * 添加/修改
     *
     * @param adTypeDto
     * @return
     */
    @Override
    public Boolean edit(AdTypeDTO adTypeDto) {
        AdTypeDO adTypeEntity = BeanUtil.toBean(adTypeDto, AdTypeDO.class);
        return this.updateById(adTypeEntity);
    }

    /**
     * 获取父角色下的所有角色
     *
     * @param parentId
     * @return
     */
    @Override
    public List<AdTypeVO> getAllList(Integer parentId) {
        LambdaQueryWrapper<AdTypeDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdTypeDO::getParentId, parentId);
        queryWrapper.orderByDesc(AdTypeDO::getId);

        List<AdTypeDO> typeList = this.list(queryWrapper);

        List<AdTypeVO> adTypeVoList = typeList.stream().map(item ->
                BeanUtil.toBean(item, AdTypeVO.class)
        ).collect(Collectors.toList());

        for (AdTypeVO adTypeVo : adTypeVoList) {
            List<AdTypeVO> childrenList = getAllList(adTypeVo.getId());
            if (childrenList != null && childrenList.size() > 0) {
                adTypeVo.setChildren(childrenList);
            }
        }

        return adTypeVoList;
    }

    /**
     * 更新排序
     *
     * @param adTypeDTO
     * @return
     */
    @Override
    public Boolean updateSort(AdTypeDTO adTypeDTO) {
        AdTypeDO adTypeEntity = new AdTypeDO();
        adTypeEntity.setId(adTypeDTO.getId());
        adTypeEntity.setSort(adTypeDTO.getSort());
        return this.updateById(adTypeEntity);
    }

    /**
     * 更新状态
     *
     * @param adTypeDTO
     * @return
     */
    @Override
    public Boolean updateStatus(AdTypeDTO adTypeDTO) {
        AdTypeDO adTypeEntity = new AdTypeDO();
        adTypeEntity.setId(adTypeDTO.getId());
        adTypeEntity.setStatus(adTypeDTO.getStatus());
        return this.updateById(adTypeEntity);
    }

}
